package de.dopichaj.labrador.index.meta;


import java.io.File;
import java.io.IOException;

import org.apache.commons.lang.Validate;
import org.apache.log4j.Logger;

import de.dopichaj.labrador.index.Tag;
import de.dopichaj.labrador.util.io.BitOutputStream;
import de.dopichaj.labrador.util.io.ByteWriter;


/**
 * An output stream for gradually constructing a document digest.
 * The caller is responsible for making sure that the digest is well-formed
 * (every opened element must be closed).
 */
public final class DocumentDigestOutputStream implements DocumentMetaDataWriter {

    private static final Logger log = Logger
        .getLogger(DocumentDigestOutputStream.class);
    private final BitOutputStream output;
    private int level = 0;
    private boolean betweenDocuments = true;
    private int id = 0;
    private int[] previousTags = new int[0];
    private int previousTagsPos;

    public DocumentDigestOutputStream(ByteWriter output) {
        this.output = new BitOutputStream(output);
    }
    
    /* (non-Javadoc)
     * @see de.dopichaj.labrador.index.DocumentMetaDataWriter#startDocument(java.io.File)
     */
    public void startDocument(File file) throws IOException {
        
        Validate.isTrue(level == 0,
            "startDocument may be called on level 0 only");
        if (!betweenDocuments) {
            throw new IllegalStateException("Inside document");
        }
        betweenDocuments = false;

        for (int i = 0; i < previousTags.length; i++) {
            previousTags[i] = i;
        }
        previousTagsPos = 0;
        
        output.writeString(file.getPath());
        output.writeBits(id, 31);
    }
    
    /* (non-Javadoc)
     * @see de.dopichaj.labrador.index.DocumentMetaDataWriter#endDocument()
     */
    public void endDocument() throws IOException {
        if (betweenDocuments) {
            throw new IllegalStateException("Outside document");
        }
        if (level > 0) {
            throw new IllegalStateException("Not all elements closed");
        }
        betweenDocuments = true;
        output.flush();
    }

    /* (non-Javadoc)
     * @see de.dopichaj.labrador.index.DocumentMetaDataWriter#openElement(de.dopichaj.labrador.index.Tag)
     */
    public void openElement(Tag tag) throws IOException {
        if (betweenDocuments) {
            throw new IllegalStateException("Outside document");
        }
        id++;
        output.writeBits(DocumentDigest.OPEN, 2);
        int id = tag.getId();
        int i = 0;
        while (i < previousTags.length && previousTags[i] != id) {
            i++;
        }
        if (i < previousTags.length) {
            if (log.isDebugEnabled()) {
                log.debug("Hit at " + i + " for " + id);
            }
            output.writeGamma(i + 1);
        } else {
            output.writeGamma(tag.getId() + previousTags.length + 1);
        }
        if (previousTags.length > 0) {
            previousTags[previousTagsPos] = id;
            previousTagsPos = (previousTagsPos + 1) % previousTags.length;
        }
        if (log.isDebugEnabled()) {
            log.debug("STATopen: " + tag.getId());
        }
        level++;
    }
    
    /* (non-Javadoc)
     * @see de.dopichaj.labrador.index.DocumentMetaDataWriter#closeElement()
     */
    public void closeElement() throws IOException {
        if (betweenDocuments) {
            throw new IllegalStateException("Outside document");
        }
        output.writeBits(DocumentDigest.CLOSE, 2);
        level--;
        Validate.isTrue(level >= 0);
    }
    
    /* (non-Javadoc)
     * @see de.dopichaj.labrador.index.DocumentMetaDataWriter#text(int)
     */
    public void text(int wordCount) throws IOException {
        if (wordCount < 0) {
            throw new IllegalArgumentException("word count should be >= 0, is " +
                wordCount);
        }
        if (betweenDocuments) {
            throw new IllegalStateException("Outside document");
        }
        internalText(wordCount);
    }
    
    private void internalText(int wordCount) throws IOException {
        if (wordCount > 0) {
            if (log.isDebugEnabled()) {
                log.debug("STATtext: " + wordCount);
            }
            output.writeBits(DocumentDigest.TEXT_LONG, 2);
            output.writeVariableLengthInt(wordCount);
        }
    }

    /* (non-Javadoc)
     * @see de.dopichaj.labrador.index.DocumentMetaDataWriter#getId()
     */
    public int getId() {
        return id;
    }

    /* (non-Javadoc)
     * @see de.dopichaj.labrador.index.DocumentMetaDataWriter#close()
     */
    public void close() throws IOException {
        if (!betweenDocuments) {
            throw new IllegalStateException("Inside document");
        }
        output.flush();
        output.close();
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/